<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>牛牛 ToDo</title>
    <link rel="shortcut icon" href="/static/favico.ico">
    <!-- 引入 Element UI 的样式 -->
    <link rel="stylesheet" href="/static/element-chalk-index.css">
    <script src="/static/jquery-3.7.1.min.js"></script>
    <!-- 引入 Vue.js -->
    <script src="/static/vue@2.js"></script>
    <!-- 引入 Element UI 的组件库 -->
    <script src="../static/element-ui-index.js"></script>
    <script src="../static/dayjs.min.js"></script>

</head>
<body>
<div id="app">
    <el-container>
        <el-header>
            <div class="header-logo">
                <img src="../static/niu.png" alt="logo" width="60px"/>
                <span class="header-name">牛牛 ToDo</span>
                <div class="header-menu">
                    <el-menu :default-active="activeIndex" class="el-menu-demo"
                             background-color="#cf9236"
                             text-color="#ffd04b"
                             active-text-color="#fff"
                             mode="horizontal" @select="handleSelect">
                        <el-menu-item index="1">待办</el-menu-item>
                        <el-menu-item index="2">已办</el-menu-item>
                        <el-menu-item index="3">已删除</el-menu-item>

                    </el-menu>
                </div>
            </div>

            <div class="current-date-time">{{ currentDateTime }}</div>
        </el-header>
        <el-main class="main-content">
            <!-- 待办-->
            <div v-if="activeIndex === '1'">
                <div class="toolbar">
                    <el-input v-model="searchQuery" placeholder="请输入任务内容" style="width: 200px;"></el-input>
                    <el-button type="warning" @click="searchTasks" style="margin-left: 10px;">搜索</el-button>
                    <el-button type="warning" @click="addTaskDialogVisible = true">添加任务</el-button>
                </div>
                <el-table  :data="pendingTasks" style="width: 100%; margin-top: 20px;"
                          :row-class-name="tableRowClassName"
                          :default-sort="{prop: 'planTime', order: 'ascending'}"
                >
                    <el-table-column type="index" :index="newindex" label="序号" width="50"></el-table-column>
                    <el-table-column sortable prop="priority" label="优先级" width="100"
                                     :formatter="formatterPriority"></el-table-column>
                    <el-table-column prop="content" label="任务内容"></el-table-column>
                    <el-table-column sortable prop="planTime" label="计划完成日期" width="140"
                                     :formatter="formatterDate"></el-table-column>
                    <el-table-column prop="createTime" label="创建日期" width="100"
                                     :formatter="formatterDate"></el-table-column>
                    <el-table-column label="操作" width="250">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑
                            </el-button>
                            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
                            </el-button>
                            <el-button size="mini" type="success"
                                       @click="showCompletionDialog(scope.$index, scope.row)">完成
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage1"
                        :page-size="pageSize"
                        layout="total,prev, pager, next"
                        :total="total"
                        style="margin-top: 20px; text-align: right;">
                </el-pagination>
            </div>
            <!--  已办-->
            <div v-else-if="activeIndex === '2'">
                <el-timeline>
                    <el-timeline-item v-for="(task, index) in completedTasks" :key="index" :timestamp="formattereDate(task.completeTime)"
                                      placement="top">
                        <el-card>
<!--                            <p>优先级: {{ formatterPriority(task) }}</p>-->
                            <h4>{{ task.content }}</h4>
<!--                            <p>计划完成日期: {{ formattereDate(task.planTime) }}</p>-->
                            <p v-if="task.note">备注: {{ task.note }}</p>
<!--                            <p>任务创建日期: {{ formattereDate(task.createTime) }}</p>-->
                            <el-button size="mini" type="warning" @click="resetToPending(index, task)">重置为待办</el-button>
                        </el-card>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <!--删除-->
            <div v-else-if="activeIndex === '3'">
                <div class="toolbar">
                    <el-input v-model="searchQuery3" placeholder="请输入任务内容" style="width: 200px;"></el-input>
                    <el-button type="warning" @click="searchTasks" style="margin-left: 10px;">搜索</el-button>
                </div>
                <el-table :data="deletedTasks"  style="width: 100%; margin-top: 20px;"
                          :row-class-name="tableRowClassName"
                          :default-sort="{prop: 'priority', order: 'ascending'}"
                >
                    <el-table-column type="index" :index="newindex3" label="序号" width="50"></el-table-column>
                    <el-table-column sortable prop="priority" label="优先级" width="100"
                                     :formatter="formatterPriority"></el-table-column>
                    <el-table-column prop="content" label="任务内容"></el-table-column>
                    <el-table-column sortable prop="planTime" label="计划完成日期" width="140"
                                     :formatter="formatterDate"></el-table-column>
                    <el-table-column prop="createTime" label="创建日期" width="100"
                                     :formatter="formatterDate"></el-table-column>
                    <el-table-column label="操作" width="250">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger"
                                       @click="deleteTaskPermanently(scope.$index, scope.row)">彻底删除
                            </el-button>
                            <el-button size="mini" type="primary"
                                       @click="resetToPending(scope.$index, scope.row)">重置为待办
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                        background
                        @size-change="handleSizeChange3"
                        @current-change="handleCurrentChange3"
                        :current-page="currentPage3"
                        :page-size="pageSize3"
                        layout="total,prev, pager, next"
                        :total="total3"
                        style="margin-top: 20px; text-align: right;">
                </el-pagination>

            </div>

        </el-main>

        <el-backtop ></el-backtop>
        <el-footer>
            <a href="#" class="about-link">明日复明日，明日何其多。我生待明日，万事成蹉跎。</a>
        </el-footer>
    </el-container>

    <!-- 添加任务对话框 -->
    <el-dialog title="添加任务" :visible.sync="addTaskDialogVisible" width="50%">
        <el-form :model="newTask" label-position="right" label-width="120px">
            <el-form-item label="优先级" :rules="[{ required: true, message: '请选择优先级', trigger: 'blur' }]">
                <el-radio-group v-model="newTask.priority">
                    <el-radio :label="1">高</el-radio>
                    <el-radio :label="2">中</el-radio>
                    <el-radio :label="3">低</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="任务内容" label-width="100px"
                          :rules="[{ required: true, message: '请输入任务内容', trigger: 'blur' }]">
                <el-input type="textarea" maxlength="1000"
                          show-word-limit clearable
                          :autosize="{ minRows: 10}"
                          v-model="newTask.content" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="计划完成日期" :rules="[{ required: true, message: '请选择计划完成日期', trigger: 'blur' }]">
                <el-date-picker type="date" placeholder="选择日期" v-model="newTask.planTime"
                                style="width: 100%;"></el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button @click="addTaskDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addTask">确 定</el-button>
            </span>
    </el-dialog>

    <!-- 编辑任务对话框 -->
    <el-dialog title="编辑任务" :visible.sync="editTaskDialogVisible" width="50%">
        <el-form :model="editingTask" label-position="right" label-width="120px">
            <el-form-item label="优先级" :rules="[{ required: true, message: '请选择优先级', trigger: 'blur' }]">
                <el-radio-group v-model="editingTask.priority">
                    <el-radio :label="1">高</el-radio>
                    <el-radio :label="2">中</el-radio>
                    <el-radio :label="3">低</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="任务内容" label-width="100px"
                          :rules="[{ required: true, message: '请输入任务内容', trigger: 'blur' }]">
                <el-input type="textarea" maxlength="1000"
                          show-word-limit clearable
                          :autosize="{ minRows: 10}"
                          v-model="editingTask.content" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="计划完成日期" :rules="[{ required: true, message: '请选择计划完成日期', trigger: 'blur' }]">
                <el-date-picker type="date" placeholder="选择日期" v-model="editingTask.planTime"
                                style="width: 100%;"></el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editTaskDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditTask">确 定</el-button>
    </span>
    </el-dialog>

</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                activeIndex: '1',
                pendingTasks: [],
                completedTasks: [],
                deletedTasks: [],
                addTaskDialogVisible: false,
                newTask: {
                    priority: 1,
                    content: '',
                    planTime: '',
                    createTime: ''
                },
                currentPage1: 1,
                pageSize: 10,
                total: 0,
                currentPage3: 1,
                pageSize3: 10,
                total3: 0,
                completionNote: '',
                editingTask: {},
                editingTaskIndex: -1,
                editTaskDialogVisible: false,
                searchQuery: '',
                searchQuery3: '',
                currentDateTime: ''
            };
        },
        computed: {
        },
        methods: {
            formatterPriority(row) {
                if (row.priority === 1) {
                    return '高';
                } else if (row.priority === 2) {
                    return '中';
                } else if (row.priority === 3) {
                    return '低';
                } else {
                    return ''
                }
            },
            formatterDate(row, column, cellValue) {
                return dayjs(cellValue).format('YYYY-MM-DD');
            },
            formattereDate(value){
                return dayjs(value).format('YYYY-MM-DD');
            },
            newindex(index){
                const page = this.currentPage1 // 当前页码
                const pagesize = this.pageSize // 每页条数
                return index + 1 + (page - 1) * pagesize
            },
            newindex3(index){
                const page = this.currentPage3 // 当前页码
                const pagesize = this.pageSize3 // 每页条数
                return index + 1 + (page - 1) * pagesize
            },
            handleSizeChange(newSize) {
                this.pageSize = newSize;
                this.fetchPendingTasks(); // 如果需要在改变页大小时重新获取数据
            },
            handleSizeChange3(newSize) {
                this.pageSize3 = newSize;
                this.fetchDeletedTasks(); // 如果需要在改变页大小时重新获取数据
            },
            handleCurrentChange(newPage) {
                this.currentPage1 = newPage;
                this.fetchPendingTasks(); // 如果需要在改变页码时重新获取数据
            },
            handleCurrentChange3(newPage) {
                this.currentPage3 = newPage;
                this.fetchDeletedTasks(); // 如果需要在改变页码时重新获取数据
            },
            tableRowClassName({row}) {
                const planTime = new Date(row.planTime);
                const today = new Date();
                const threeDaysLater = new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000);
                if (planTime <= today) {
                    return 'danger-row';
                }
                if (planTime > today && planTime <= threeDaysLater) {
                    return 'warning-row';
                }
                return '';
            },
            handleSelect(key) {
                this.activeIndex = key;
                if (key === '1') {
                    this.fetchPendingTasks();
                } else if (key === '2') {
                    this.fetchCompletedTasks();
                } else if (key === '3') {
                    this.fetchDeletedTasks();
                }
            },
            addTask() {
                if (this.newTask.content.trim() === '') {
                    this.$message.error('任务内容不能为空');
                    return;
                }
                if (this.newTask.planTime === '') {
                    this.$message.error('计划完成日期不能为空');
                    return;
                }
                this.newTask.createTime = dayjs().valueOf();
                this.newTask.planTime = dayjs(this.newTask.planTime).valueOf();
                var task = {
                    priority: this.newTask.priority,
                    content: this.newTask.content,
                    planTime: this.newTask.planTime,
                    createTime: this.newTask.createTime
                }
                fetch("/addTask", {
                    method: "POST",
                    body: JSON.stringify(task),
                    headers: {
                        "Content-type": "application/json"
                    }
                }).then(res => {
                    return res.json();
                }).then(todo => {
                    if (todo.success){
                        this.$message({
                            message: '添加成功',
                            type: 'success',
                            duration:2000
                        });
                        this.fetchPendingTasks();
                    }
                });
                this.newTask.content = '';
                this.newTask.planTime = '';
                this.addTaskDialogVisible = false;
            },
            handleDelete(index, row) {
                fetch("/deleteTask", {
                    method: "POST",
                    body: JSON.stringify(row),
                    headers: {
                        "Content-type": "application/json"
                    }
                }).then(res => {
                    return res.json();
                }).then(todo => {
                    if (todo.success){
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration:1000
                        });
                        this.fetchPendingTasks();
                    }
                });
            },
            searchTasks() {
                // 搜索逻辑已经在computed属性中实现
                this.searchQuery = this.searchQuery.trim();
                this.fetchPendingTasks();
            },
            searchTasks3() {
                // 搜索逻辑已经在computed属性中实现
                this.searchQuery3 = this.searchQuery3.trim();
                this.fetchDeletedTasks();
            },
            handleEdit(index, row) {
                this.editingTask = {...row};
                this.editingTaskIndex = index;
                this.editTaskDialogVisible = true;
            },
            saveEditTask() {
                if (this.editingTask.content.trim() === '') {
                    this.$message.error('任务内容不能为空');
                    return;
                }
                if (this.editingTask.planTime === '') {
                    this.$message.error('计划完成日期不能为空');
                    return;
                }
                this.editingTask.planTime = dayjs(this.editingTask.planTime).valueOf();
                fetch("/editTask", {
                    method: "POST",
                    body: JSON.stringify(this.editingTask),
                    headers: {
                        "Content-type": "application/json"
                    }
                }).then(res => {
                    return res.json();
                }).then(todo => {
                    if (todo.success){
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                            duration:1000
                        });
                        this.fetchPendingTasks();
                    }
                });

                this.editTaskDialogVisible = false;
            },
            showCompletionDialog(index, row) {
                this.$prompt('请输入备注（非必填）', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /.*/,
                    inputPlaceholder: '请输入备注（非必填）',
                    inputValue: '', // 初始值为空
                    inputValidator: () => {
                        return true; // 不进行验证，允许为空
                    }
                }).then(({value}) => {
                    row.note=value;
                    fetch("/completeTask", {
                        method: "POST",
                        body: JSON.stringify(row),
                        headers: {
                            "Content-type": "application/json"
                        }
                    }).then(res => {
                        return res.json();
                    }).then(todo => {
                        if (todo.success){
                            this.$message({
                                message: '任务完成',
                                type: 'success',
                                duration:1000
                            });
                            this.fetchPendingTasks();
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            resetToPending(index, row) {
                fetch("/resetToPending", {
                    method: "POST",
                    body: JSON.stringify(row),
                    headers: {
                        "Content-type": "application/json"
                    }
                }).then(res => {
                    return res.json();
                }).then(todo => {
                    if (todo.success){
                        this.$message({
                            message: '已重置为待办',
                            type: 'success',
                            duration:1000
                        });
                        if (this.activeIndex === '1') {
                            this.fetchPendingTasks();
                        } else if (this.activeIndex === '2') {
                            this.fetchCompletedTasks();
                        } else if (this.activeIndex === '3') {
                            this.fetchDeletedTasks();
                        }
                    }
                });
            },
            deleteTaskPermanently(index, row) {
                fetch("/realDeleteTask", {
                    method: "POST",
                    body: JSON.stringify(row),
                    headers: {
                        "Content-type": "application/json"
                    }
                }).then(res => {
                    return res.json();
                }).then(todo => {
                    if (todo.success){
                        this.$message({
                            message: '彻底删除成功',
                            type: 'success',
                            duration:1000
                        });
                        this.fetchDeletedTasks();
                    }
                });
            },
            fetchPendingTasks() {
                var content=this.searchQuery3;
                var page=this.currentPage1;
                var limit= this.pageSize;
                // 假设你使用的是axios来进行HTTP请求
                fetch('/pendingTasks?content='+content+'&page='+page+'&limit='+limit).then(response => response.json()) // 解析JSON响应
                    .then(data => {
                        this.$notify({
                            title: '成功',
                            message: '获取列表数据成功',
                            type: 'success',
                            duration: 1000
                        });
                        // 假设服务器返回的数据是一个数组
                        this.pendingTasks = data.rows;
                        this.total = data.totalRows;

                    }).catch(error => {
                    this.$notify.error({
                        title: '获取数据异常',
                        message: '获取数据异常，请稍后重试'
                    });
                });
            },
            fetchCompletedTasks() {
                fetch('/completedTasks').then(response => response.json()) // 解析JSON响应
                    .then(data => {
                        this.$notify({
                            title: '成功',
                            message: '获取列表数据成功',
                            type: 'success',
                            duration: 1000
                        });
                        // 假设服务器返回的数据是一个数组
                        this.completedTasks = data;

                    }).catch(error => {
                    this.$notify.error({
                        title: '获取数据异常',
                        message: '获取数据异常，请稍后重试'
                    });
                });
            },
            fetchDeletedTasks() {
                var content=this.searchQuery;
                var page=this.currentPage3;
                var limit= this.pageSize3;
                fetch('/deletedTasks?content='+content+'&page='+page+'&limit='+limit).then(response => response.json()) // 解析JSON响应
                    .then(data => {
                        this.$notify({
                            title: '成功',
                            message: '获取列表数据成功',
                            type: 'success',
                            duration: 1000
                        });
                        // 假设服务器返回的数据是一个数组
                        this.deletedTasks = data.rows;
                        this.total3 = data.totalRows;

                    }).catch(error => {
                    this.$notify.error({
                        title: '获取数据异常',
                        message: '获取数据异常，请稍后重试'
                    });
                });
            },
            updateCurrentDateTime() {
                this.currentDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
            },
        },
        mounted() {
            this.fetchPendingTasks();
            this.updateCurrentDateTime();
            setInterval(this.updateCurrentDateTime, 1000); // 每秒更新一次

        }
    });
</script>

<style>
    body {
        margin: 0; /* 移除默认的body边距 */
    }

    .el-header {
        position: fixed; /* 固定头部 */
        top: 0;
        left: 0;
        width: 100%;
        height: 60px;
        background-color: #cf9236;
        font-size: 20px;
        display: flex;
        align-items: center; /* 垂直居中 */
        z-index: 1000; /* 确保头部在其他内容之上 */
    }

    .header-logo {
        display: flex;
        align-items: center; /* 垂直居中 */
    }
    .current-date-time {
        color: #fff;
        font-size: 14px;
        padding-left: 62%;
    }
    .header-logo div,
    .header-logo span {
        margin: 5px; /* 可选：增加间距 */
    }

    .header-menu {
        margin-left: 10px; /* 调整菜单与logo之间的间距 */
    }

    .el-menu-demo {
        background-color: transparent; /* 去掉菜单背景色，使其与头部背景一致 */
        border-bottom: none; /* 去掉菜单底部边框 */
    }

    .main-content {
        padding-top: 70px; /* 调整主体内容的上边距，以避免被固定的头部遮挡 */
        min-height: calc(100vh - 60px); /* 确保主体内容至少占满剩余视口高度 */
        background-color: #f0f0f0; /* 设置背景颜色为灰色 */
        padding: 20px; /* 增加内边距 */
        margin-top: 50px;
    }

    .toolbar {
        display: flex;
        align-items: center; /* 垂直居中 */
        margin-bottom: 20px; /* 工具栏下方的间距 */
    }

    .about-link {
        color: #f0f0f0; /* 设置链接颜色 */
        text-decoration: none; /* 去掉下划线 */
    }

    .about-link:hover {
        text-decoration: underline; /* 鼠标悬停时显示下划线 */
    }

    .el-footer {
        bottom: 0;
        left: 0;
        right: 0;
        height: 60px;
        background-color: #cf9236; /* 设置背景颜色为灰色 */
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .el-table .warning-row {
        background: #E0E054;
    }

    .el-table .success-row {
        background: #00ff00;
    }

    .el-table .danger-row {
        background: #E7666F;
    }

    .el-timeline {
        margin-top: 20px;
    }

    .el-timeline-item__timestamp {
        font-size: 14px;
        color: #909399;
    }

    .el-card {
        margin-bottom: 20px;
    }
</style>
</body>
</html>
